package org.example.util;

import cn.hutool.core.util.ObjectUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author taoshen
 * @create 2021/4/5
 */
public class MybatisUtils {
    private MybatisUtils() {

    }

    private static SqlSessionFactory factory = null;

    static {
        try {
            String mybatis_xml = "mybatis.xml";
            InputStream is = Resources.getResourceAsStream(mybatis_xml);
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession对象的静态方法
     */
    public static SqlSession getSqlSession() throws IOException {
        if (ObjectUtil.isNotNull(factory)) {
            return factory.openSession(true);
        }
        return null;
    }
}
